const { Op } = require("sequelize");
const User = require("../../model/User");
const crypto = require("crypto");
// 登录
exports.login = async function (userName, userPwd) {
	// 验证用户
	const user = await User.findOne({
		where: {
			[Op.or]: [{ loginName: userName }, { phone: userName }],
		},
		attributes: [
			"id",
			"name",
			"phone",
			"userState",
			"loginName",
			"loginPwd",
		]
	});
	if (!user) {
    throw "用户不存在"
	}
	// 验证密码
	const isMatch = user.loginPwd === userPwd;
	// const isMatch = await bcrypt.compare(userPwd, user.loginPwd);
	if (!isMatch) {
    throw "密码错误"
	}
	// 验证状态
	if (user.userState === 0) {
		throw "用户已禁用"
	}
	const res = user.toJSON();
	delete res.loginPwd;
	return res;
};

// 注册
exports.register = async function (req) {
	const user = await User.findOne({
		where: {
			[Op.or]: [{ loginName: req.body.loginName }, { phone: req.body.phone }],
		},
		attributes: [
			"phone",
			"loginName",
		]
	});
	if (user) {
		if (user.phone === req.body.phone) {
      throw "该手机号已注册"
		}
		if (user.loginName === req.body.loginName) {
			throw "该用户名已注册"
		}
    throw "用户已存在"
	} else {
		const ins = await User.create({
			id: crypto.randomUUID(),
			name: req.body.name,
			phone: req.body.phone,
			loginName: req.body.loginName,
			loginPwd: req.body.loginPwd,
		},{
			fields: ["id", "name", "phone", "loginName", "createdAt"],
		});
		console.log(ins.toJSON(), "添加成功");
		return ins.toJSON();
	}
};
